//
//  ViewController.m
//  视频的录制和播放
//
//  Created by 梁森 on 2018/5/21.
//  Copyright © 2018年 梁森. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    NSURL * _mediaURL;
}

@property (nonatomic, strong) UIImagePickerController * imagePickerC;
@property (nonatomic, strong) AVPlayerViewController * playerViewC;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

// 采集视频
- (IBAction)pickVideo:(id)sender {
    [self presentViewController:self.imagePickerC animated:YES completion:nil];
}
// 播放视频
- (IBAction)playVideo:(id)sender {
    if (_mediaURL != nil) {
        [self.playerViewC.player play];
    }
    
}

#pragma mark --- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    // 获取媒体类型
    NSString * type = info[UIImagePickerControllerMediaType];
    // 如果是视频媒体类型
    if ([type isEqualToString:(__bridge NSString *)kUTTypeMovie]) {
        // 获取视频媒体的URL
        _mediaURL = info[UIImagePickerControllerMediaURL];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"取消了录制...");
}

- (UIImagePickerController *)imagePickerC{
    if (_imagePickerC == nil) {
        _imagePickerC = [[UIImagePickerController alloc] init];
        _imagePickerC.delegate = self;
        // 采集源
        _imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
        // 媒体类型
        _imagePickerC.mediaTypes = [NSArray arrayWithObject:(__bridge NSString *)kUTTypeMovie];
        // 视频质量
        _imagePickerC.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }
    return _imagePickerC;
}

- (AVPlayerViewController *)playerViewC{
    if (_playerViewC == nil) {
        _playerViewC = [[AVPlayerViewController alloc] init];
        _playerViewC.player = [[AVPlayer alloc] initWithURL:_mediaURL];
        // 全屏窗口
        [self presentViewController:_playerViewC animated:YES completion:nil];
        // 小屏窗口
//        _playerViewC.view = CGRectMake(0, 0, 100, 100);
//        [self.view addSubview:_playerViewC.view];
    }
    return _playerViewC;
}

@end
